package com.meilai.project.service.middleware.impl;

import com.alibaba.fastjson.JSONObject;
import com.meilai.project.dto.middleware.YunPianBehaviorVerificationDTO;
import com.meilai.project.service.middleware.YunPianService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author 张驰
 * @date 2020/12/3 11:09
 */
@Service
public class YunPianServiceImpl implements YunPianService {
    private final static Logger logger = LoggerFactory.getLogger(YunPianServiceImpl.class);
    private static String AUTH_URL = "https://captcha.yunpian.com/v1/api/authenticate";

    @Value("${behavior-verification.yunpian-APPID}")
    private String APPID;
    @Value("${behavior-verification.yunpian-secretId}")
    private String secretId;
    @Value("${behavior-verification.yunpian-secretKey}")
    private String secretKey;
    @Value("${sms.yunpian-key}")
    private String apikey;

    @Override
    public String getBehaviorVerificationAPPID() {
        return APPID;
    }

    @Override
    public JSONObject getShorten(String longUrl, String name) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("apikey", apikey);
        paramMap.put("long_url", longUrl);
        paramMap.put("name", StringUtils.defaultString(name,""));

        PostMethod postMethod = new PostMethod("https://sms.yunpian.com/v2/short_url/shorten.json");
        postMethod.addRequestHeader("Accept", "application/json;charset=utf-8");
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        paramMap.forEach((k, v) -> {
            postMethod.addParameter(k, v);
        });
        HttpClient httpClient = new HttpClient();
        try{
            int status = httpClient.executeMethod(postMethod);
            logger.info("请求结果:{}", postMethod.getResponseBodyAsString());
            if(status == 200) {
                JSONObject obj = JSONObject.parseObject(postMethod.getResponseBodyAsString());
                if(obj.getString("code").equals("0") && obj.getString("msg").toLowerCase().equals("ok")){
                    return obj.getJSONObject("short_url");
                } else {
                    return null;
                }
            }else{
                return null;
            }
        }catch (Exception e){
            logger.error("生成短链接请求失败",e);
            return null;
        }
    }

    @Override
    public boolean behaviorVerification(YunPianBehaviorVerificationDTO dto) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("captchaId", APPID);
        paramMap.put("secretId", secretId);
        paramMap.put("token", dto.getToken());
        paramMap.put("authenticate", dto.getAuthenticate());
        paramMap.put("version", "1.0");
        paramMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
        paramMap.put("nonce", String.valueOf(new Random().nextInt(99999)));

        String signature = genSignature(secretKey, paramMap);
        paramMap.put("signature", signature);

        StringBuilder sb = new StringBuilder();
        PostMethod postMethod = new PostMethod(AUTH_URL);
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        paramMap.forEach((k, v) -> {
            postMethod.addParameter(k, v);
        });
        HttpClient httpClient = new HttpClient();
        try{

            int status = httpClient.executeMethod(postMethod);
            if(status == 200) {
                JSONObject obj = JSONObject.parseObject(postMethod.getResponseBodyAsString());
                //return false;
                return (obj.get("code").toString().equals("0") && obj.get("msg").equals("ok"));
            }else{
                return false;
            }
        }catch (Exception e){
            logger.error("行为验证请求失败",e);
            return false;
        }
    }

    // generate signature
    private static String genSignature(String secretKey, Map<String, String> params) {
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            sb.append(key).append(params.get(key));
        }
        sb.append(secretKey);
        return DigestUtils.md5Hex(sb.toString());
    }
}
